package com.ruiysoft.crm.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.QueryChainWrapper;
import com.google.common.collect.Lists;
import com.ruiysoft.crm.log.InvokeLog;
import com.ruiysoft.crm.model.ApiResponseEx;
import com.ruiysoft.crm.model.dto.AllocationDTO;
import com.ruiysoft.crm.model.dto.BizClientDTO;
import com.ruiysoft.crm.model.dto.MoveDataDTO;
import com.ruiysoft.crm.model.entity.*;
import com.ruiysoft.crm.model.vo.BizClientVo;
import com.ruiysoft.crm.model.vo.PolicyVo;
import com.ruiysoft.crm.model.vo.Response;
import com.ruiysoft.crm.service.*;
import com.ruiysoft.crm.util.ExcelListener;
import com.ruiysoft.crm.util.HttpClient;
import com.ruiysoft.crm.util.Query;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.alibaba.excel.EasyExcelFactory.read;
import static com.alibaba.excel.EasyExcelFactory.readSheet;

/**
 * @author fanyl
 */
@Slf4j
@Api(tags = "客户信息")
@RestController
@RequestMapping("/client")
public class BizClientController {

    private final BizClientService bizClientService;

    private final IBizCallLogService callLogService;

    private final BizPolicyService bizPolicyService;

    private final BizSmsService smsService;
    ApiResponseEx apiResponseEx = new ApiResponseEx();

    private final SysUserService sysUserService;

    private final BizBatchClientRecordService bizBatchClientRecordService;

    @GetMapping("/rejectList")
    public IPage rejectList(Integer page, Integer limit) {
        Page feny = new Page();
        feny.setCurrent(page);
        feny.setSize(limit);

        return bizClientService.rejectList(feny);
    }

    @GetMapping("/batchNuFindDetail")
    public IPage batchNuFindDetail(String batchNu, Integer page, Integer limit) {
        Page feny = new Page();
        feny.setCurrent(page);
        feny.setSize(limit);

        return bizBatchClientRecordService.batchNuFindDetail(feny, batchNu);
    }

    public BizClientController(BizClientService bizClientService, IBizCallLogService callLogService, BizPolicyService bizPolicyService, BizSmsService smsService, SysUserService sysUserService, BizBatchClientRecordService bizBatchClientRecordService) {
        this.bizClientService = bizClientService;
        this.callLogService = callLogService;
        this.bizPolicyService = bizPolicyService;
        this.smsService = smsService;
        this.sysUserService = sysUserService;
        this.bizBatchClientRecordService = bizBatchClientRecordService;
    }

    @GetMapping("/rejectSellData")
    public Object rejectSellData(Integer id) {
        BizClient bizClient = bizClientService.getById(id);
        if(bizClient != null) {
            bizClient.setRemark(bizClient.getUserName() + ", 退回的数据");
            bizClient.setUserId(null);
            bizClient.setUserName(null);
            bizClient.setModificationDate(LocalDateTime.now());
            bizClient.setSuccess("reject");

            if(bizClientService.updateById(bizClient))
                return Response.success();

        }
        return Response.failure("退回失败");
    }

    /**
     * 通过ID查询信息
     *
     * @param id ID
     * @return
     */
    @InvokeLog
    @GetMapping("/get/{id}")
    public BizClient get(@PathVariable Integer id) {
        return bizClientService.getClientById(id);
    }

    /**
     * 分页查询
     *
     * @param params 分页对象
     * @return 分页对象
     */
    @InvokeLog
    @ApiOperation(value = "条件查询客户车辆信息", notes = "条件查询客户车辆信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "客户id", dataType = "Integer"),
            @ApiImplicitParam(name = "mobilePhone", value = "联系电话", dataType = "String"),
            @ApiImplicitParam(name = "carNo", value = "车牌号", dataType = "String"),
            @ApiImplicitParam(name = "firstRegistrationDate", value = "初登日期", dataType = "String")
    })
    @GetMapping("/list/page")
    public IPage dictPage(@RequestParam Map<String, Object> params, HttpServletRequest request) {

        String userId = request.getHeader("userId");
        if (StringUtils.isEmpty(userId)) {
            SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getUsername, "hanl"));
            userId = String.valueOf(sysUser.getUserId());
            params.put("enterprise_id",sysUser.getEnterpriseId());
        }
        if (!StringUtils.isEmpty(userId) ) {
                params.put("client.user_id", userId);
        }

        String successValue = (String) params.get("success");
        if("-1".equals(successValue) || StringUtils.isEmpty(successValue)){
            params.put("success", "IFNULL(client.success,'-1') = '-1' ");
        } else {
            params.put("success", "IFNULL(client.success,'') in ('" + successValue + "')");
        }

        Boolean isAsc = Boolean.parseBoolean(params.getOrDefault("isAsc", Boolean.TRUE).toString());
        String orderByField = (String) params.get("orderByField");
        if (orderByField != null) {
            params.put("order", orderByField);
            params.put("desc", isAsc ? "asc" : "desc");
        }
        return bizClientService.queryClientInfo(new Query<>(params), params);
    }


    /**
     * 分页查询
     *
     * @param params 分页对象
     * @return 分页对象
     */
    @InvokeLog
    @ApiOperation(value = "条件查询客户车辆信息", notes = "条件查询客户车辆信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "客户id", dataType = "Integer"),
            @ApiImplicitParam(name = "mobilePhone", value = "联系电话", dataType = "String"),
            @ApiImplicitParam(name = "carNo", value = "车牌号", dataType = "String"),
            @ApiImplicitParam(name = "firstRegistrationDate", value = "初登日期", dataType = "String")
    })
    @GetMapping("/list/pageManage")
    public IPage dictPageManage(@RequestParam Map<String, Object> params, HttpServletRequest request) {

        String userId = null;
        if(!StringUtils.isEmpty((String) params.get("yewyId"))){
            userId=(String) params.get("yewyId");
        }

        if (!StringUtils.isEmpty(userId))
            params.put("client.user_id", userId);

        SysUser sysUser = sysUserService.getById(request.getHeader("userId"));
        params.put("enterprise_id",sysUser.getEnterpriseId());
        String successValue = (String) params.get("success");

        if("-1".equals(successValue) || StringUtils.isEmpty(successValue)){
          //  params.put("success", "IFNULL(client.success,'-1') = '-1' ");
        } else {
            params.put("success", "IFNULL(client.success,'') in ('" + successValue + "')");
        }

        Boolean isAsc = Boolean.parseBoolean(params.getOrDefault("isAsc", Boolean.TRUE).toString());
        String orderByField = (String) params.get("orderByField");
        if (orderByField != null) {
            params.put("order", orderByField);
            params.put("desc", isAsc ? "asc" : "desc");
        }
        return bizClientService.queryClientInfo(new Query<>(params), params);
    }

    /**
     * 添加
     *
     * @param bizClient 客户信息
     * @return success、false
     */
    @InvokeLog
    @ApiOperation(value = "插入客户信息", notes = "插入客户信息")
    @PostMapping("/insert")
    public Response add(@RequestBody BizClient bizClient, HttpServletRequest request) {
        String userId = request.getHeader("userId");

        bizClient.setCreateDate(LocalDateTime.now());

        if (StringUtils.hasText(userId)) {
            SysUser sysUser = sysUserService.getById(userId);
            bizClient.setUserId(Integer.valueOf(userId));
            bizClient.setEnterpriseId(sysUser.getEnterpriseId());
            bizClient.setUserName(sysUser.getRealName());
        }
        if (!ObjectUtils.isEmpty(bizClientService.getOne(new QueryWrapper<BizClient>().eq("car_no", bizClient.getCarNo())))) {
            return Response.failure("此客户已经存在，不能重复添加");
        }
        if (bizClientService.save(bizClient)) {
            return Response.success(bizClient);
        }
        return Response.failure("添加客户失败！");
    }


    /**
     * 根据userID获取分类数据记录数
     *
     * @return
     */
    @GetMapping("/getSuccessCountByUserId")
    public Response getSuccessCountByUserId(HttpServletRequest request) {
        String userId = request.getHeader("userId");
        if ("19".equals(userId)) {
            userId = null;
        }
        List<BizClient> clients = bizClientService.getSuccessCountByUserId(userId);
        int total = 0;
        for (int i = 0; clients != null && i < clients.size(); i++) {
            total += clients.get(i).getSeating() == null ? 0 : clients.get(i).getSeating();
        }

        List<PolicyVo> policyVos = bizPolicyService.queryPolicyListByUserId(userId);
        if (policyVos != null && policyVos.size() > 0) {
            BizClient client = new BizClient();
            client.setLabel("已出单");
            client.setSeating(policyVos.get(0).getUserId());
            clients.add(client);
        }

        if (clients != null && clients.size() > 0) {
            BizClient client = new BizClient();
            client.setLabel("合计");
            client.setSeating(total);
            clients.add(client);
        }

        return Response.success(clients);
    }


    /**
     * 删除
     *
     * @param id 客户id
     * @return R
     */
    @InvokeLog
    @DeleteMapping("/delete/{id}")
    public Response delete(@PathVariable Integer id) {
        return Response.success(bizClientService.removeById(id));
    }

    /**
     * 修改
     *
     * @param bizClient 客户信息
     * @return success/false
     */
    @InvokeLog
    @PutMapping("/update")
    public Response editDict(@RequestBody BizClient bizClient) {
        bizClient.setModificationDate(LocalDateTime.now());

        if (bizClient.getMobilePhone() != null && bizClient.getMobilePhone().contains("****")) {
            bizClient.setMobilePhone(null);
        }
        if (bizClient.getStandbyMobile() != null && bizClient.getStandbyMobile().contains("****")) {
            bizClient.setStandbyMobile(null);
        }

        return Response.success(bizClientService.updateById(bizClient));
    }

    /**
     * 根据批次号撤销数据
     *
     * @param id
     * @return
     */
    @InvokeLog
    @PutMapping("/revoke/{id}")
    public Response revoke(@PathVariable Integer id) {
        Assert.notNull(id, "id不能为空");

        BizBatchClientRecord record = bizBatchClientRecordService.getById(id);
        if (ObjectUtils.isEmpty(record)) {
            return Response.failure("批次记录不存在");
        }

       /* int[] ids = Arrays.stream(record.getClientIds().split(",")).mapToInt(Integer::parseInt).toArray();
        String clientIds = org.apache.commons.lang3.StringUtils.join(ids, ",");*/

        if (bizClientService.revokeAllotUser(record)) {
            return Response.success("撤销数据成功");
        }

        return Response.failure("数据批次撤销失败");
    }

    /**
     * @param userId 离职员工id
     * @return com.ruiysoft.crm.model.vo.Response
     * @Description 离职员工数据回收
     * @date 7:22 下午 2019/12/1
     * @author fanyl
     */
    @PutMapping("/retrieve/{userId}")
    public Response retrieveClient(@PathVariable Integer userId) {
        Assert.notNull(userId, "userId不能为空");
        List<BizClient> clientList = bizClientService.list(new QueryWrapper<BizClient>().lambda().eq(BizClient::getUserId, userId));

        clientList.forEach(bizClient -> {
            bizClient.setUserId(null);
            bizClient.setUserName(null);
            bizClient.setSuccess(null);
        });

        if (bizClientService.updateBatchById(clientList)) {
            List<Integer> clientIds = clientList.stream().map(BizClient::getId).collect(Collectors.toList());
            SysUser sysUser = sysUserService.getById(userId);
            bizBatchClientRecordService.insert(clientIds, userId, "retrieve", "回收员工【" + sysUser.getRealName() + "】的客户数据", sysUser.getRealName());
            return Response.success("回收员工【" + sysUser.getRealName() + "】的客户数据成功");
        }
        return Response.failure("回收数据失败");
        //UpdateWrapper<BizClient> updateWrapper = new UpdateWrapper<>();
        //updateWrapper.set("success", null);
        //updateWrapper.set("user_id", null);
        //updateWrapper.set("user_name", null);
        //updateWrapper.eq("user_id", userId);


    }

    /**
     * @param params
     * @param request
     * @return cn.taroco.common.web.Response
     * @Description 根据条件查询结果分配客户至业务员
     * @date 8:00 下午 2019/11/3
     * @author fanyl
     */
    @InvokeLog
    @ApiOperation(value = "根据条件查询结果分配客户至业务员")
    @PostMapping("/allocation")
    public Response allocationToUser(@RequestBody Map<String, Object> params, HttpServletRequest request) {

        if (ObjectUtils.isEmpty(params)) {
            return Response.failure("分配数据不能为空！");
        }
        String userId = request.getHeader("userId");

        //去除分页排序参数
        params.remove("page");
        params.remove("limit");
        params.remove("isAsc");

        List<String> ids = (List<String>) params.get("yewy_ids");
        List<SysUser> users = (List<SysUser>) sysUserService.listByIds(ids);

        params = params.entrySet().stream().filter((e) -> !ObjectUtils.isEmpty(e.getValue()))
                .collect(Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue()));

//        if (StringUtils.isEmpty(userId)) {
//            SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getUsername, "hanl"));
//            userId = String.valueOf(sysUser.getUserId());
//        }
        SysUser sysUser=sysUserService.getById(userId);
        params.put("enterprise_id",sysUser.getEnterpriseId());
        if (!StringUtils.isEmpty(userId) && !"-1".equals(userId) && !"null".equals(userId)) {
            params.put("client.user_id", userId);
        }

        params.remove("yewy_ids");
        List<BizClient> bizClients = bizClientService.allocationToUser(params);

        Map<Integer, List<BizClient>> clientMaps = splitList(bizClients, users);
        List<Object> res = new ArrayList<>();
        for (int i = 0; i < users.size(); i++) {
            List<BizClient> clis = clientMaps.get(users.get(i).getUserId());
            for (BizClient bizClient : clis) {
                bizClient.setModificationDate(LocalDateTime.now());
                bizClient.setUserId(users.get(i).getUserId());
                bizClient.setAllocationDate(LocalDateTime.now());
                bizClient.setUserName(users.get(i).getUsername());
            }
            if (bizClientService.updateBatchById(clis)) {
                List<Integer> clientIds = clis.stream().map(BizClient::getId).collect(Collectors.toList());
                bizBatchClientRecordService.insert(clientIds, users.get(i).getUserId(), "allot", null, users.get(i).getRealName());
                Map<String, String> ss = new HashMap<>();
                ss.put("userId", users.get(i).getUserId() + "");
                ss.put("userName", users.get(i).getRealName());
                ss.put("total", clis.size() + "");
                res.add(ss);
            }
        }
        if (res != null && res.size() > 0) {
            return Response.success(res);
        }


        return Response.failure("分配数据失败");
    }

    /**
     * @return cn.taroco.common.web.Response
     * @Description 选择客户并分配至业务员
     * @Date 8:00 下午 2019/11/3
     * @Param allocationDTO
     * @Author fanyl
     */
    @InvokeLog
    @ApiOperation(value = "选择客户并分配至业务员")
    @PostMapping("/assign")
    public Response assignClientToUser(@RequestBody AllocationDTO allocationDTO) {
        if (allocationDTO.getClientIds() != null && allocationDTO.getClientIds().size() < 1) {
            return Response.failure("分配数据不能为空！");
        }

        int userId = allocationDTO.getUserId();
        SysUser userVO = sysUserService.getById(userId);
        String userName = userVO.getRealName();
        List<BizClient> bizClients = new ArrayList<>();
        allocationDTO.getClientIds().forEach(
                clientId -> {
                    BizClient bizClient = new BizClient();
                    bizClient.setModificationDate(LocalDateTime.now());
                    bizClient.setId(clientId);
                    bizClient.setUserId(userId);
                    bizClient.setAllocationDate(LocalDateTime.now());
                    bizClient.setUserName(userName);
                    bizClients.add(bizClient);
                }
        );
        if (bizClientService.updateBatchById(bizClients)) {
            List<Integer> clientIds = bizClients.stream().map(BizClient::getId).collect(Collectors.toList());
            bizBatchClientRecordService.insert(clientIds, userId, "allot", null, userName);
            return Response.success(true);
        }
        return Response.failure("分配数据失败");
    }


    @InvokeLog
    @ApiOperation(value = "移动数据")
    @PutMapping("/moveData")
    public Response moveData(@RequestBody MoveDataDTO moveDataDTO) {
        if (ObjectUtils.isEmpty(moveDataDTO)) {
            return Response.failure("移动数据不能为空！");
        }
        List<BizClient> bizClients = new ArrayList<>();
        moveDataDTO.getIds().forEach(
                clientId -> {
                    BizClient bizClient = new BizClient();
                    bizClient.setModificationDate(LocalDateTime.now());
                    bizClient.setId(clientId);
                    if (StringUtils.hasText(moveDataDTO.getStatus())) {
                        bizClient.setSuccess(moveDataDTO.getStatus());
                    }
                    bizClients.add(bizClient);
                }
        );
        return Response.success(bizClientService.updateBatchById(bizClients));
    }


    /**
     * excel方式导入客户数据
     *
     * @param file       excel文件
     * @param remark     备注
     * @param isValidate 是否严格校验
     * @param request
     * @return
     */
    @InvokeLog
    @PostMapping("/excelImport")
    public Response excelImport(@RequestParam("file") MultipartFile file,
                                @RequestParam("remark") String remark,
                                @RequestParam("isValidate") String isValidate,
                                @RequestParam("insurer") String insurerCode,
                                HttpServletRequest request) {
        Response response = new Response();
        JSONObject jsonObject = new JSONObject();

        String str_userId = request.getHeader("userId");
        Integer userId = null;
        SysUser sysUser = null;
        if (str_userId != null) {
            userId = Integer.parseInt(str_userId);
            sysUser = sysUserService.getById(userId);
        }

        //导入数据保存失败列表
        List<String> failList = Lists.newArrayList();
        //导入用户数据集合
        List<BizClientDTO> clientDTOList = Lists.newArrayList();
        //有效用户数据集合
        List<BizClientDTO> clientList = null;
        int totalNum = 0;

        try {
            ExcelListener<BizClientDTO> excelListener = new ExcelListener();
            ExcelReader excelReader = read(file.getInputStream(), BizClientDTO.class, excelListener).build();
            ReadSheet readSheet = readSheet(0).build();
            excelReader.read(readSheet);
            excelReader.finish();

            // excel 导入的数据
            clientDTOList = excelListener.getDataList();
            if (CollectionUtils.isEmpty(clientDTOList)) {
                return Response.failure("导入数据不能为空");
            }

//            for (BizClientDTO bizClientDTO: clientDTOList
//                 ) {
//                bizClientDTO.setEnterpriseId(sysUser.getEnterpriseId());
//                System.out.println(bizClientDTO.getEnterpriseId());
//            }

            totalNum = clientDTOList.size();
//            //查询库中所有的车牌号
            List<String> carNos = bizClientService.getCarNos();
//            List<String> enterpriseCode = bizClientService.getEnterpriseCode();

            if (!CollectionUtils.isEmpty(carNos)) {
                //过滤导入数据中的重复数据和数据库中已存在数据（根据车牌号)
//                clientList = clientDTOList.stream()
//                        .filter(bizClientDTO -> !carNos.contains(bizClientDTO.getCarNo())).filter(bizClientDTO -> !enterpriseCode.contains(bizClientDTO.getEnterpriseId())).collect(Collectors.toList());
                clientList = new ArrayList<>();

                if (!CollectionUtils.isEmpty(clientList)) {
                    clientList = Lists.newArrayList(clientList).stream().filter(bizClientDto -> StringUtils.hasText(bizClientDto.getCarNo())).collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BizClientDTO::getCarNo))), ArrayList::new));
                }

                //车牌重复列表
                clientDTOList.removeAll(clientList);
            }


            List<String> repeatList = clientDTOList.stream().map(BizClientDTO::getCarNo).collect(Collectors.toList());

            if (!CollectionUtils.isEmpty(repeatList)) {
                jsonObject.put("repeat", String.format("重复车牌号:【%s】", org.apache.commons.lang.StringUtils.join(repeatList, ",")));
            }

        } catch (IOException e) {
            log.error("excel文件解析失败：{}", e);
        }

        List<Integer> clientIds = Lists.newArrayList();
        StringBuilder message = new StringBuilder();


        List<BizClient> listBatch = new ArrayList<>();

        for (int i = 0; i < clientDTOList.size(); i++) {
            BizClientDTO bizClientDTO = clientDTOList.get(i);
            BizClient bizClient = new BizClient();

            try {
                String[] ignoreFields = new String[]{"firstRegistrationDate", "viEndDate", "clivtaEndDate"};
                BeanUtils.copyProperties(bizClientDTO, bizClient, ignoreFields);

                bizClient.setInsurerCode(insurerCode);
                bizClient.setEnterpriseId(sysUser.getEnterpriseId());

                if (ObjectUtil.isNull(bizClientDTO.getUserId())) {
                    bizClient.setUserId(userId);
                }

                bizClient.setCreateDate(LocalDateTime.now());
                bizClient.setModificationDate(LocalDateTime.now());

                if ("1".equals(isValidate)) {
                    String carNo = bizClient.getCarNo();
                    String standbyMobile = bizClient.getStandbyMobile();
                    String mobilePhone = bizClient.getMobilePhone();
                    String idCard = bizClient.getInsuredIdCard();
                    String insured = bizClient.getInsured();
                    String engineNumber = bizClient.getEngineNumber();
                    String vehicleNo = bizClient.getVehicleNo();

                    if (StringUtils.hasText(standbyMobile)) {
                        if (!phoneNumber(standbyMobile)) {
                            message.append("  客户电话2格式错误 \n");
                        }
                    }

                    if (StringUtils.hasText(mobilePhone)) {
                        if (!phoneNumber(mobilePhone)) {
                            message.append("  客户电话1格式错误 \n");
                        }
                    } else {
                        message.append("  客户电话1不能为空 \n");
                    }

                    if (StringUtils.hasText(idCard)) {
                        if (!idCardNumber(idCard)) {
                            message.append("  被保险人证件号错误 \n");
                        }
                    } else {
                        message.append("  被保险人证件号不能为空\n");
                    }
                    if (StringUtils.isEmpty(insured)) {
                        message.append("  被保险人姓名不能为空\n");
                    }
                    if (StringUtils.isEmpty(carNo)) {
                        message.append("  车牌号不能为空\n");
                    }
                    if (StringUtils.isEmpty(engineNumber)) {
                        message.append("  发动机号不能为空\n");
                    }
                    if (StringUtils.isEmpty(vehicleNo)) {
                        message.append("  车架号不能为空\n");
                    }
                    if (message.length() > 0) {
                        message.insert(0, "第" + (i + 1) + "条数据存在问题，不允许导入，原因：\n");
                        continue;
                    }
                }

                String firstRegistrationDate = bizClientDTO.getFirstRegistrationDate();
                String clivtaEndDate = bizClientDTO.getClivtaEndDate();
                String viEndDate = bizClientDTO.getViEndDate();

                if (!ObjectUtils.isEmpty(firstRegistrationDate)) {
                    bizClient.setFirstRegistrationDate(formatDate(firstRegistrationDate));
                }
                if (!ObjectUtils.isEmpty(clivtaEndDate)) {
                    bizClient.setClivtaEndDate(formatDate(clivtaEndDate));
                }
                if (!ObjectUtils.isEmpty(viEndDate)) {
                    bizClient.setViEndDate(formatDate(viEndDate));
                }

//                try {
//                    // 这里要改成批量插入
//                    if (bizClientService.save(bizClient)) {
//                        clientIds.add(bizClient.getId());
//                    }
//                } catch (Exception e) {
//                    failList.add(bizClient.getCarNo());
//                    log.error("插入失败{}", e);
//                }

                listBatch.add(bizClient);

            } catch (Exception e) {
                failList.add(bizClient.getCarNo());
                log.error("插入失败{}", e);
                continue;
            }
        }

        if (message.length() > 0) {
            return Response.failure(message.toString());
        }

        if(listBatch.size() > 0 && bizClientService.saveBatch(listBatch)) {
            clientIds = listBatch.stream().map(BizClient::getId).collect(Collectors.toList());

            if (!CollectionUtils.isEmpty(clientIds)) {
                //批次号对应数据记录，可根据批次号删除数据
                bizBatchClientRecordService.insert(clientIds, userId, "import", remark, null);
            }
        }

        if (!CollectionUtils.isEmpty(failList)) {
            jsonObject.put("fail", String.format("新增失败车牌号:【%s】", org.apache.commons.lang.StringUtils.join(failList, ",")));
        }
        response.setResult(jsonObject);
        response.setExtMessage("导入数据总数：" + totalNum + ";实际导入：" + listBatch.size() + ";失败：" + (totalNum - clientIds.size()));
        return response;
    }

    /**
     * 批量删除销售数据
     *
     * @param ids 需要删除的数据id集合
     * @return Response 删除结果
     */
    @InvokeLog
    @ApiOperation(value = "批量删除销售数据")
    @Transactional(rollbackFor = Exception.class)
    @DeleteMapping("/delete/batch")
    public Response deleteBatch(@RequestBody List<Integer> ids) {
        if (ObjectUtils.isEmpty(ids)) {
            return Response.failure("参数不能为空");
        }
        return Response.success(bizClientService.removeByIds(ids));
    }


    /**
     * 验证手机号
     *
     * @param number 手机号
     * @return boolean
     */

    private boolean phoneNumber(String number) {
        String rgx = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
        return isCorrect(rgx, number);
    }

    /**
     * 验证身份证号
     *
     * @param number 身份证号
     * @return boolean
     */
    private boolean idCardNumber(String number) {
        String rgx = "^\\d{15}|^\\d{17}([0-9]|X|x)$";
        return isCorrect(rgx, number);
    }

    /**
     * 正则验证
     *
     * @param rgx 正则表达式
     * @param res 验证字符串
     * @return boolean
     */
    private static boolean isCorrect(String rgx, String res) {
        Pattern p = Pattern.compile(rgx);
        if (res == null) {
            return true;
        }
        Matcher m = p.matcher(res);
        return m.matches();
    }


    private LocalDate formatDate(String date) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        return LocalDate.parse(date, formatter);
    }


    @InvokeLog
    @PostMapping("/recv_center")
    public Response recv_center(@RequestBody BizSms bizSms, HttpServletRequest request) {
        String str = "";
        int userId = Integer.parseInt(request.getHeader("userId"));
        SysUser sysUser = sysUserService.getById(userId);

        try {
            BizClient client = bizClientService.getClientById(Integer.parseInt(bizSms.getClientid()));
            String mobileNo = "";
            if ("1".equals(bizSms.getTag())) {
                mobileNo = client.getMobilePhone();
            } else {
                mobileNo = client.getStandbyMobile();
            }
            String url = "http://qxt.fungo.cn/Recv_center?CpName=hwxy&CpPassword=190722&DesMobile=" + mobileNo + "&Content=" + bizSms.getContent() + "&ExtCode=12";
            str = HttpClient.sendPostRequest(url, null);
            JSONObject objecj = JSONObject.parseObject(str);
            BizSms sms = new BizSms();
            sms.setClientid(bizSms.getClientid());
            sms.setClientname(client.getCarOwner());
            sms.setContent(bizSms.getContent());
            sms.setCreateTime(new Date());
            sms.setMobileno(mobileNo);
            sms.setSmstype("sms");
            sms.setEnterpriseId(sysUser.getEnterpriseId());
            sms.setValidflag("0");
            sms.setUpdateTime(new Date());
            sms.setUserid(userId + "");
            sms.setUsername(sysUser.getUsername());
            if ("0".equals(objecj.get("code"))) {
                sms.setValidflag("1");
            } else {
                sms.setValidflag("0");
            }
            sms.setNote(str);
            smsService.save(sms);
        } catch (Exception e) {
            BizSms sms = new BizSms();
            str = e.toString();
            sms.setNote(str);
            sms.setClientid(bizSms.getClientid());
            sms.setClientname("");
            sms.setContent(bizSms.getContent());
            sms.setCreateTime(new Date());
            sms.setMobileno("");
            sms.setEnterpriseId(sysUser.getEnterpriseId());
            sms.setSmstype("sms");
            sms.setUpdateTime(new Date());
            sms.setUserid("");
            sms.setValidflag("0");
            sms.setUsername(sysUser.getUsername());
            smsService.save(sms);
        }
        return Response.success(str);
    }

    @PostMapping("/recv_center_return")
    public void recv_center_return(String args) {
        String[] arg = args.split(",");
        System.out.println(arg.toString());
        QueryChainWrapper<BizSms> sms = smsService.query().like("note", arg[0]);
        List<BizSms> sms1 = sms.list();
        if (sms1 != null && sms1.size() > 0) {
            BizSms s = sms1.get(0);
            s.setValidflag("0".equalsIgnoreCase(arg[2]) ? "2" : arg[2]);
            smsService.save(s);
        }

    }


    @ApiOperation(value = "根据客户ID查询短信列表", notes = "根据客户ID查询短信列表")
    @GetMapping("/getSms")
    public ApiResponseEx getSMS(@RequestParam Map<String, Object> params, HttpServletRequest request) throws Exception {
        int userId = Integer.parseInt(request.getHeader("userId"));
       // SysUser sysUser = sysUserService.getById(userId);
       // int userId = sysUserService.getUserIdByUserName(userVO.getUsername());
        apiResponseEx.setData(smsService.getSMS(params, userId));
        return apiResponseEx;
    }

    /**
     * 分页查询
     *
     * @param params 分页对象
     * @return 分页对象
     */
    @ApiOperation(value = "条件查询客户车辆信息", notes = "条件查询客户车辆信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "客户id", dataType = "Integer"),
            @ApiImplicitParam(name = "mobilePhone", value = "联系电话", dataType = "String"),
            @ApiImplicitParam(name = "carNo", value = "车牌号", dataType = "String"),
            @ApiImplicitParam(name = "firstRegistrationDate", value = "初登日期", dataType = "String")
    })
    @InvokeLog
    @GetMapping("/list/batch")
    public IPage batchPage(@RequestParam Map<String, Object> params) {
        StringBuilder createIds = new StringBuilder();
//            IPage<BizBatchClientRecord> page=new I
        //  bizBatchClientRecordService.page(new Query<>(params));
        Wrapper<BizBatchClientRecord> batch = new QueryWrapper<>();
        ((QueryWrapper<BizBatchClientRecord>) batch).orderByDesc("create_date");
        return bizBatchClientRecordService.page(new Query<>(params), batch);
    }


    @InvokeLog
    @ApiOperation(value = "按照批次ID分配数据")
    @PutMapping("/allocationByBatchid")
    public Response allocationByBatchid(String batchid, String userId) {
        SysUser userVO = sysUserService.getById(userId);
        //String userName = userVO.getRealName();
        return Response.success(bizClientService.allocationByBatchid(batchid, userVO));
    }


    @GetMapping("/export")
    public void exportData(@RequestParam Map<String, Object> params, HttpServletResponse response) {

        List<BizClientVo> bizClients = bizClientService.queryClients(params);

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        try {
            String fileName = URLEncoder.encode("客户数据", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), BizClientVo.class).sheet("客户数据").doWrite(bizClients);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param list  需要分的集合
     * @param users 分的份数
     */
    public static Map<Integer, List<BizClient>> splitList(List<BizClient> list, List<SysUser> users) {
        int listSize = list.size();

        //用户封装返回的多个list
        HashMap<Integer, List<BizClient>> stringListHashMap = new HashMap<Integer, List<BizClient>>();
        //用于承装每个等分list
        List<BizClient> stringlist = null;

        for (int i = 0; i < listSize; i++) {
            stringlist = stringListHashMap.get(users.get((i + 1) % users.size()).getUserId());
            if (stringlist == null) {
                stringlist = new ArrayList<BizClient>();
            }
            System.out.println((i + 1) % users.size());
            //先将string对象放入list,以防止最后一个没有放入
            stringlist.add(list.get(i));
            // if (((i+1) % users.size() == 0)||(i+1==listSize)) {               //如果l+1 除以 要分的份数 为整除,或者是最后一份,为结束循环.那就算作一份list,
            //将这一份放入Map中.
            stringListHashMap.put(users.get((i + 1) % users.size()).getUserId(), stringlist);
            // stringlist = new ArrayList<BizClient>();                //新建一个list,用于继续存储对象
            //  }
        }

        return stringListHashMap;
    }

}
